package com.lq.springai.config;

import com.lq.springai.entity.ModelParams;
import io.micrometer.observation.ObservationRegistry;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.model.tool.ToolCallingManager;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.ai.ollama.management.ModelManagementOptions;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AIConfig {


    public ChatClient chatClient(ModelParams modelParams) {

        OpenAiApi api = new OpenAiApi(modelParams.getBaseUrl(),modelParams.getApiKey());

        OpenAiChatOptions aiChatOptions = OpenAiChatOptions.builder().build();
        aiChatOptions.setModel(modelParams.getModelName());
        aiChatOptions.setTemperature(modelParams.getTemperature());

        OpenAiChatModel model = new OpenAiChatModel(api,aiChatOptions);

        return ChatClient.builder(model).build();
    }

    public OllamaChatModel ollamaChatModel(ModelParams modelParams){

        log.info("开始与ollama建立连接...");

        //1、建立与ollama连接通信
        OllamaApi ollamaApi = new OllamaApi(modelParams.getBaseUrl());

        //2、配置参数
        OllamaOptions options = OllamaOptions.builder()
                .model(modelParams.getModelName())
                .temperature(modelParams.getTemperature())
                .build();

        //3、支持工具调用
        ToolCallingManager toolCallingManager = ToolCallingManager.builder().build();

        //4、监控
        ObservationRegistry observationRegistry = ObservationRegistry.NOOP;

        //5、模型管理配置
        ModelManagementOptions modelManagementOptions = ModelManagementOptions.defaults();

        log.info("创建ollama连接对象...");
        //6、创建
        OllamaChatModel ollamaChatModel = new OllamaChatModel(ollamaApi,options,toolCallingManager,observationRegistry,modelManagementOptions);

        log.info("ollama连接对象创建完成...");

        return ollamaChatModel;
    }

}
